<template>
  <div>
    <!-- The toolbar will be rendered in this container. -->
    <div id="toolbar-container" :style="{ width: titlewidth }"></div>
    <!-- This container will become the editable. -->
    <div id="editor" :style="{ height, border: 'solid 1px #ccc', width }">
      <!--<p>This is the initial editor content.</p>-->
    </div>
    <!--<el-button @click="getContent">获取编辑器的内容</el-button>-->
  </div>
</template>

<script>
import Vue from 'vue'
// 组件内使用this.$apis.apiName调用
import Apis from '@/apis'

Vue.prototype.$apis = Apis
// console.log("富文本=======",Apis.getUploadUrl())
//重点代码 适配器
class UploadAdapter {
  constructor(loader) {
    this.loader = loader
  }

  upload() {
    var _this = this
    return new Promise((resolve, reject) => {
      const data = new FormData()
      let file = []
      //this.loader.file 这是一个Promise格式的本地文件流，一定要通过.then 进行获取，之前在各大博客查了很多文章都拿不到这个值，最后经过两个多小时的探索终于找到了是Promise问题。
      this.loader.file.then(res => {
        file = res //文件流
        data.append('file', file) //传递给后端的参数，参数名按照后端需求进行填写
        console.log('富文本上传文件========', file)
        // data.append('type','1');
        // data.append('bucketName','xydms');/传递给后端的参数，参数名按照后端需求进行填写
        // data.append('ckCsrfToken','oCS0feM9aUb0v4zQqrEgcExpQeWTZXG4pch37uds');/传递给后端的参数，参数名按照后端需求进行填写
        // data.append('objectName','1101053001');/传递给后端的参数，参数名按照后端需求进行填写
        $.ajax({
          // url: 'https://www.xiaoyoushengxue.com/sxgh/file/upload', //后端的上传接口
          // url: 'https://www.xiaoyoushengxue.com/mpp/file/upload', //后端的上传接口
          url: Apis.getUploadUrl() + '/file/upload',
          type: 'POST',
          data: data,
          dataType: 'json',
          processData: false,
          contentType: false,
          success: function (res) {
            if (res.result == 0) {
              console.log(res)
              resolve({
                default: res.data.url //后端返回的参数 【注】返回参数格式是{uploaded:1,default:'http://xxx.com'}
              })
            } else {
              reject(res.data.msg)
            }
          }
        })
      })
    })
  }

  abort() {
  }
}

export default {
  // props: ['content', 'type', 'height', 'width', 'titlewidth'],
  props: {
    content: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    height: {
      type: String,
      default: '500px'
    },
    width: {
      type: String,
      default:''
      // default: 'calc(100% - 2px)'
    },
    titlewidth: {
      type: String,
      default: '100%'
    }
  },
  name: 'ckeditor',
  data() {
    return {}
  },
  create() {
  },
  mounted() {
    //实例化编辑器
    DecoupledEditor.create(document.querySelector('#editor'), {
      removePlugins: ['Table', 'MediaEmbed'],
      // ckfinder: {
      // 	uploadUrl: 'upload'
      // },
      language: 'zh',
      toolbar: {
        items: [
          'heading',
          '|',
          // 'fontfamily',
          'fontsize',
          '|',
          'alignment',
          '|',
          'fontColor',
          'fontBackgroundColor',
          '|',
          'bold',
          'italic',
          'strikethrough',
          'underline',
          'subscript',
          'superscript',
          '|',
          'link',
          '|',
          'outdent',
          'indent',
          '|',
          'bulletedList',
          'numberedList',
          'todoList',
          '|',
          'insertTable',
          '|',
          'blockQuote',
          '|',
          'undo',
          'redo',
          '|',
          'imageUpload'
          // 'imageStyle:full',
          // 'imageStyle:side',
        ],
        shouldNotGroupWhenFull: true
      },
      indentBlock: {
        offset: 1,
        unit: 'em'
      },
      /*fontFamily: {
            options: [
              'default',
              '宋体',
              '仿宋',
              '微软雅黑',
              '楷体',
              '黑体',
              'Arial, Helvetica, sans-serif',
              'Courier New, Courier, monospace',
              'Georgia, serif',
              'Lucida Sans Unicode, Lucida Grande, sans-serif',
              'Tahoma, Geneva, sans-serif',
              'Times New Roman, Times, serif',
            ],
          },*/
      fontSize: {
        options: [
          9,
          11,
          12,
          'default',
          16,
          18,
          20,
          22,
          24,
          26,
          28,
          30,
          32,
          34,
          36,
          38,
          40
        ]
      }
    })
      .then(editor => {
        const toolbarContainer = document.querySelector('#toolbar-container')
        toolbarContainer.appendChild(editor.ui.view.toolbar.element)
        // 加载了适配器
        editor.plugins.get('FileRepository').createUploadAdapter = loader => {
          return new UploadAdapter(loader)
        }
        window.editor = editor
        // window.editor.isReadOnly = true; //将编辑器设为只读
        // var e_content='<p style=\"text-align:center;\"><span class=\"text-big\"><strong>This is the initial editor content.</strong></span></p><figure class=\"image image_resized\" style=\"width:347px;\"><img src=\"https://xiaoyoushengxue.com/2022041620211307.jpg\"></figure><p><strong>哈哈哈哈哈</strong></p>'
        var e_content = this.content
        // console.log('ckeditor==============', this.content)
        if (e_content == undefined) {
          window.editor.setData('')
        } else {
          window.editor.setData(e_content)
        }
        if (this.type == 'info') {
          window.editor.enableReadOnlyMode('information_ck_id') //打开只读模式
        } else {
          window.editor.disableReadOnlyMode('information_ck_id') //关闭只读模式（“清除锁定”）
        }
      })
      .catch(error => {
        console.error('Oops, something gone wrong!')
        console.error(
          'Please, report the following error in the https://github.com/ckeditor/ckeditor5 with the build id and the error stack trace:'
        )
        console.warn('Build id: kngfcngsrrab-jujsj4qk5w31')
        console.error(error)
      })

    // function clickMe(){
    //   console.log(window.editor.getData()) //获取编辑器的内容 getData()
    // }
  },
  methods: {
    getContent() {
      console.log(window.editor.getData()) //获取编辑器的内容 getData()
      this.content = window.editor.getData()
    }
  }
}
</script>

<style scoped lang="scss">
.ck-content {
  //padding: 0 !important;
  //padding: 1em;
  //width: calc(100% - 2px);
}
</style>
